/*
 * 文件名： CustEduCertifyJob.java
 * 
 * 工程名称: 20160623_cron_xuanguanghai
 *
 * Gopay
 *
 * 创建日期： 2016年6月23日
 *
 * Copyright(C) 2016, by www.gopay.com.cn Inc.All rights reserved.
 *
 * 原始作者: 宣广海
 *
 */
package com.gopay.scheduler.job;

import java.util.*;

import javax.annotation.Resource;

import com.gopay.common.cipher.utils.LoggerMaskUtils;
import com.gopay.common.user.manager.PersonThreeAccountChannelManager;
import com.gopay.common.util.DateUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.common.Result;
import com.gopay.common.domain.bank.foundation.IdentityInfoMessage;
import com.gopay.common.domain.user.identify.PersCertChannelDTL;
import com.gopay.common.exception.GopayException;
import com.gopay.common.order.dao.CommonQueryDAO;
import com.gopay.common.user.dao.PersCertChannelDtlDao;
import com.gopay.remote.bank.BisCertificationRemoteService;
import com.gopay.scheduler.GopayBaseJob;
import com.gopay.scheduler.job.vo.CertiryGZTVo;

/**
 * 学历认证
 *
 * @author 宣广海
 *
 * @version
 *
 * @since 2016年6月23日
 */
public class CustEduCertifyJob extends GopayBaseJob {

	private Logger logger = LoggerFactory.getLogger(CustEduCertifyJob.class);

	@Resource(name = "commonQueryDAO")
	private CommonQueryDAO commonQueryDAO;
	@Resource(name = "bisCertificationRemoteService")
	private BisCertificationRemoteService bisCertificationRemoteService;
	@Resource(name = "persCertChannelDtlDao")
	PersCertChannelDtlDao persCertChannelDtlDao;

	@Resource(name = "personThreeAccountChannelManager")
	private PersonThreeAccountChannelManager personThreeAccountChannelManager;

	/**
	 * 学历认证渠道
	 */
	private String eduCertChannel;
	private boolean certificateFlag;

	@Override
	protected void doJobInternal() {

		logger.info("学历认证任务开始，认证渠道是：" + eduCertChannel);
		/**
		 * 查询出已实名已认证的，并且在日志表中不存在国政通学历认证过的数据
		 */
		List<Object[]> custList = queryEduCustList(eduCertChannel);

//		List<Object[]> custList=new ArrayList<>();
//		Object[] obj1={"0000002390","刘珊珊","23052319860902002X"};
//		Object[] obj2={"0000001814","刘珊珊","23052319860902002X"};
//		Object[] obj3={"0000008170","王强","37040419841201225X"};
//		Object[] obj4={"0000008280","东楠","110103198602280940"};
//		Object[] obj5={"0000008182","苏璇","130124198510031264"};
//		Object[] obj6={"0000008021","刘娜","320381198307050340"};

//		custList.add(0, obj1);
//		custList.add(1, obj2);
//		custList.add(2, obj3);
//		custList.add(3, obj4);
//		custList.add(4, obj5);
//		custList.add(5, obj6);
		if (custList != null && custList.size() > 0) {
			logger.error("需要做学历渠道：" + eduCertChannel + "学历认证的数量为： " + custList.size());
			int successCount = 0;
			for (Object[] obj : custList) {
				try {

					//add by songfengli 20180312 判断是否需要调用第三方服务
					if(null != obj[0] && null != obj[2]){
						if(!personThreeAccountChannelManager.isTransferCertChannel(obj[2].toString(),obj[0].toString())){
							continue;
						}
					}

					CertiryGZTVo certiryGZTVo = new CertiryGZTVo();
					if(null!=obj[0]){
						certiryGZTVo.setCustId(obj[0].toString());
					}
					if(null!=obj[1]){
						certiryGZTVo.setCustName(obj[1].toString());
					}
					if(null!=obj[2]){
						certiryGZTVo.setCertNo(obj[2].toString());
					}		
					// 调用渠道进行学历认证
					if(certificateFlag){
					exeEduCertify(certiryGZTVo,eduCertChannel);
					}
					successCount++;

				} catch (GopayException e) {
					logger.error("学历认证失败,certId:" +  obj[0].toString());
					e.printStackTrace();
				} catch (Exception e) {
					logger.error("学历认证失败,certId:" +  obj[0].toString());
					e.printStackTrace();
				}
			}
			logger.error("学历认证的完成数量为： " + successCount);
			logger.info("学历认证任务结束。");
		} else {
			logger.info("没有需要学历认证的数据.");
		}

	}

	/**
	 * 
	 * 功能描述：查询出已实名已认证,并且在认证日志表中不存在学历渠道认证过的数据
	 *
	 * @param eduCertChannel
	 *            学历认证渠道
	 * @return
	 * 
	 * @author 宣广海
	 *
	 * @since 2016年6月24日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	private List<Object[]> queryEduCustList(String eduCertChannel) {
		StringBuilder sb = new StringBuilder();
		sb.append("select distinct(c.cust_id),c.cust_name,c.cert_no from cust_person_info c  ")
				.append(" left join pers_cert_channel_dtl p  on c.cust_id=p.cust_id ")
				.append(" where c.is_real_name_certify ='1' ") // 已实名已认证
				.append(" and  not exists ")
				.append(" (select cust_id from  pers_cert_channel_dtl p where p.cust_id=c.cust_id and p.channel_code =:channelCode )");
		//新增时间限制条件 只认证两天内的 未认证记录 生产bug7期 lx 2017-7-24 10:32:21
		sb.append(" and p.created_ts>=to_date(:startDate,'yyyymmdd') ");
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("channelCode", eduCertChannel);
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		calendar.add(Calendar.DAY_OF_MONTH, -2); //两天内
		String startDate= DateUtils.format(calendar.getTime(), "yyyyMMdd");

		paramMap.put("startDate", startDate);

		return commonQueryDAO.findBySql(sb.toString(), paramMap);
	}

	/**
	 * 
	 * 功能描述：调用学历认证接口
	 *
	 * @param certiryGZTVo
	 * @param eduCertChannel
	 * @throws GopayException
	 * 
	 * @author 宣广海
	 *
	 * @since 2016年6月24日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	private void exeEduCertify(CertiryGZTVo certiryGZTVo, String eduCertChannel) throws GopayException {
		IdentityInfoMessage base = new IdentityInfoMessage();
		base.setCardHolder(certiryGZTVo.getCustName());
		base.setIdentityCode(certiryGZTVo.getCertNo());
		logger.info("IdentityInfoMessage==== 姓名：" + base.getCardHolder() + "，身份证号：" + LoggerMaskUtils.maskString(base.getIdentityCode()));
		try {
			String certStatus = null;
			/**
			 * 调用学历认证接口
			 */
			Result certResult = bisCertificationRemoteService.queryValidator(base);

			logger.error("bisCertificationRemoteService queryValidator result: "
					+  LoggerMaskUtils.maskString(ToStringBuilder.reflectionToString(certResult)));
			if (certResult.isSuccess()) {
				if((Boolean) certResult.getModel("flag")){
					certStatus = "01";	
				}
				else {				
					certStatus = "02";
				}
				addEduCertChannel(certiryGZTVo, eduCertChannel, certStatus);
			}else{
				logger.info("========调用国政通学历认证接口失败======失败原因："+certResult.getErrorMsg());
			}
		} catch (Exception e) {
			logger.info("========调用国政通学历认证接口失败======");
			throw new GopayException("调用学历认证接口失败" + e);
		}
	}

	public void addEduCertChannel(CertiryGZTVo certiryGZTVo, String eduCertChannel, String status) {
		// 增加国政通认证渠道 add by gaocl 20160519("01":国政通)
		PersCertChannelDTL persCertChannel = persCertChannelDtlDao.findByCustIdAndChannel(certiryGZTVo.getCustId(),
				eduCertChannel);

		if (null == persCertChannel) {
			PersCertChannelDTL persCertChannelDTL = new PersCertChannelDTL();
			persCertChannelDTL.setCertNo(certiryGZTVo.getCertNo());
			persCertChannelDTL.setChannelCode(eduCertChannel);
			persCertChannelDTL.setCustId(certiryGZTVo.getCustId());
			persCertChannelDTL.setCreatedOperId(certiryGZTVo.getCustId());
			persCertChannelDTL.setCreatedTs(new Date());
			persCertChannelDTL.setStatus(status);
			persCertChannelDTL.setRemark("国政通学历认证");
			logger.info("新增国政通渠道信息===========" +  LoggerMaskUtils.maskString(persCertChannelDTL.toString()));
			personThreeAccountChannelManager.savePersCertChannel(persCertChannelDTL);
		}
	}

	/**
	 * @return 返回 eduCertChannel。
	 */
	public String getEduCertChannel() {
		return eduCertChannel;
	}
    /**
	 * @param eduCertChannel
	 *            要设置的 eduCertChannel。
	 */
	public void setEduCertChannel(String eduCertChannel) {
		this.eduCertChannel = eduCertChannel;
	}

	public boolean isCertificateFlag() {
		return certificateFlag;
	}

	public void setCertificateFlag(boolean certificateFlag) {
		this.certificateFlag = certificateFlag;
	}
}
